package com.li.youhappygo.interceptor;


import com.alibaba.fastjson.JSON;
import com.li.youhappygo.model.entity.system.SysUser;
import com.li.youhappygo.util.AuthContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行");

        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {      // 如果是跨域预检请求，直接放行
            return true;
        }
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            return false;
        }
        SysUser sysUser = JSON.parseObject(redisTemplate.opsForValue().get("user:login:" + token), SysUser.class);
        if(sysUser == null){
            return false;
        }
        AuthContext.setUser(sysUser);
        redisTemplate.expire("user:login:"+token, 30, TimeUnit.MINUTES);

        return true;

    }
}
